/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package helpdiabetesj2me;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 *
 * @author Johan VM Windows 7
 */
public class Utilities {

    
    /**
     * example 10:20, hours and minutes local time
     */
    public static String getHHmmAsString(Date dateToFormat) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateToFormat);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        TimeZone timeZone = calendar.getTimeZone();
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        
        String returnValue;
        returnValue = "";
        //returnValue = Integer.toString(year);
        //returnValue += "-";
        //returnValue += (Integer.toString(month).length() == 2 ? Integer.toString(month) : "0" + Integer.toString(month));
        //returnValue += "-";
        //returnValue += (Integer.toString(date).length() == 2 ? Integer.toString(date) : "0" + Integer.toString(date));
        //returnValue += "T";
        returnValue += (Integer.toString(hour).length() == 2 ? Integer.toString(hour) : "0" + Integer.toString(hour));
        returnValue += ":";
        returnValue += (Integer.toString(minute).length() == 2 ? Integer.toString(minute) : "0" + Integer.toString(minute));
        //returnValue += ":";
        //returnValue += (Integer.toString(second).length() == 2 ? Integer.toString(second) : "0" + Integer.toString(second));
        //returnValue += "Z";
        return returnValue;
    }

    /**
     * example 2014-12-01, year, month and date, local time
     */
    public static String getYearAndDateAsString(Date dateToFormat) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateToFormat);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int date = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        TimeZone timeZone = calendar.getTimeZone();
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        
        String returnValue;
        returnValue = "";
        returnValue = Integer.toString(year);
        returnValue += "-";
        returnValue += (Integer.toString(month).length() == 2 ? Integer.toString(month) : "0" + Integer.toString(month));
        returnValue += "-";
        returnValue += (Integer.toString(date).length() == 2 ? Integer.toString(date) : "0" + Integer.toString(date));
        //returnValue += "T";
        //returnValue += (Integer.toString(hour).length() == 2 ? Integer.toString(hour) : "0" + Integer.toString(hour));
        //returnValue += ":";
        //returnValue += (Integer.toString(minute).length() == 2 ? Integer.toString(minute) : "0" + Integer.toString(minute));
        //returnValue += ":";
        //returnValue += (Integer.toString(second).length() == 2 ? Integer.toString(second) : "0" + Integer.toString(second));
        //returnValue += "Z";
        return returnValue;
    }
    
    
    public static String replace(String source, String pattern, String replacement)
	{	
	
		//If source is null then Stop
		//and return empty String.
		if (source == null)
		{
			return "";
		}

		StringBuffer sb = new StringBuffer();
		//Intialize Index to -1
		//to check against it later 
		int idx = -1;
		//Intialize pattern Index
		int patIdx = 0;
		//Search source from 0 to first occurrence of pattern
		//Set Idx equal to index at which pattern is found.
		idx = source.indexOf(pattern, patIdx);
		//If Pattern is found, idx will not be -1 anymore.
		if (idx != -1)
		{
			//append all the string in source till the pattern starts.
			sb.append(source.substring(patIdx, idx));
			//append replacement of the pattern.
			sb.append(replacement);
			//Increase the value of patIdx
			//till the end of the pattern
			patIdx = idx + pattern.length();
			//Append remaining string to the String Buffer.
			sb.append(source.substring(patIdx));
		}
		//Return StringBuffer as a String

                if ( sb.length() == 0)
                {
                    return source;
                }
                else
                {
                    return sb.toString();
                }
	}
    
    /**
     * 
     * @param dateAsString in format example 2014-09-27T22:45:37.0 or 2014-09-27T22:45:33.000Z, greenwich meantime<br>
     * @return 
     */
    public static Date parseDate(String dateAsString) {
        if (dateAsString == null) return null;
        if (dateAsString.length() == 0) return null;
        Calendar calendar = Calendar.getInstance();
        try {
            String[] dateArray = split(dateAsString, "T");
            String[] date = split(dateArray[0], "-");
            String[] time = split(dateArray[1], ":");
            time[2] = split(time[2],".")[0];
            
            calendar.set(Calendar.MONTH, Integer.parseInt(date[1]) - 1);
            calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date[2]));
            calendar.set(Calendar.YEAR, Integer.parseInt(date[0]));
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
            calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
            calendar.set(Calendar.MILLISECOND, 0);
        } catch (ArrayIndexOutOfBoundsException exc) {
            return null;
        } finally {
            return calendar.getTime();
        }
    }
    
    public static String[] split(String stringToSplit, String splitter){
        String[] strs = new String[stringToSplit.length()];
        int splitterLength = splitter.length();
        int initialIndex = 0;
        int indexOfSplitter = indexOf(stringToSplit, splitter, initialIndex);
        int count = 0;
        
        if(indexOfSplitter == -1) return new String[]{stringToSplit};
        
        while(indexOfSplitter != -1){
            char[] chars = new char[indexOfSplitter - initialIndex];
            stringToSplit.getChars(initialIndex, indexOfSplitter, chars, 0);
            initialIndex = indexOfSplitter+splitterLength;
            indexOfSplitter = indexOf(stringToSplit, splitter, indexOfSplitter + 1);
            strs[count] = new String(chars);
            count++;
        }
        // get the remaining chars.
        if(initialIndex + splitterLength <= stringToSplit.length()){
            char[] chars = new char[stringToSplit.length() - initialIndex];
            stringToSplit.getChars(initialIndex, stringToSplit.length(), chars, 0);
            strs[count] = new String(chars);
            count++;
        }
        String[] result = new String[count];
        for (int i = 0; i<count; i++){
            result[i] = strs[i];
        }
        return result;
    }
    
    public static int indexOf(String findIn, String stringToFind, int start){
        StringBuffer sb;
        sb = new StringBuffer(findIn);
        
        int index;
        index = -1;
        
        if((start >= sb.length() || start <- 1) || stringToFind.length() <= 0) return index;
        
        char[] tofind = stringToFind.toCharArray();
        
        outer: for(;start<sb.length(); start++){
            char c = sb.charAt(start);
            if(c==tofind[0]){
                if(1==tofind.length) return start;
                inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
                    char find = tofind[i];
                    int currentSourceIndex = start+i;
                    if(currentSourceIndex<sb.length()){
                        char source = sb.charAt(start+i);
                        if(find==source){
                            if(i==tofind.length-1){
                                return start;
                            }
                            continue inner;
                        } else {
                            start++;
                            continue outer;
                        }
                    } else {
                        return -1;
                    }
                }
            }
        }
        return index;
    }
    
    /**
     * Encodes a URL - This method assumes UTF-8
     * @param url URL to encode
     * @return the encoded URL
 * URL Utils - UrlUtils.java
 * Author: C. Enrique Ortiz
 * Copyright (c) 2004-2012
 * C. Enrique Ortiz <enrique dot ortiz at gmail dot com>
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the 
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * Usage & redistributions of source code must retain the above copyright 
 * notice.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU Lesser General Public License for more details.
 *
 * You should get a copy of the GNU Lesser General Public License from
 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 * -----------------------------------------------------------------------
 */
    // Unreserved punctuation mark/symbols
    private static final String mark = "-_.!~*'()\"";
 
    /**
     * Converts Hex digit to a UTF-8 "Hex" character
     * @param digitValue digit to convert to Hex
     * @return the converted Hex digit
     */
    static private char toHexChar(int digitValue) {
        if (digitValue < 10)
            // Convert value 0-9 to char 0-9 hex char
            return (char)('0' + digitValue);
        else
            // Convert value 10-15 to A-F hex char
            return (char)('A' + (digitValue - 10));
    }
    
    static public String encodeURL(String url) {
    
    
        StringBuffer encodedUrl = new StringBuffer(); // Encoded URL
        int len = url.length();
        // Encode each URL character
        for(int i = 0; i < len; i++) {
            char c = url.charAt(i); // Get next character
            if  ((c >= '0' && c <= '9') ||
                (c >= 'a' && c <= 'z') ||
                (c >= 'A' && c <= 'Z')) {
                // Alphanum characters require no encoding, append as is
                encodedUrl.append(c);
            } else {
                int imark = mark.indexOf(c);
                if  (imark >=0) {
                    // Unreserved punctuation marks and symbols require
                    //  no encoding, append as is
                    encodedUrl.append(c);
                } else {
                   // Encode all other characters to Hex, using format 
                   // "%XX", where XX are the hex digits
                   encodedUrl.append('%'); // Add % character
                   // Encode the character's high-order nibble to Hex
                   encodedUrl.append(toHexChar((c & 0xF0) >> 4));
                   // Encode the character's low-order nibble to Hex
                   encodedUrl.append(toHexChar (c & 0x0F));
                }
            }
        }
        return encodedUrl.toString(); // Return encoded URL
    }
    
}
